# backend/api/v1/users.py - 修复后的完整版本
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from backend.database import get_db
from backend.schemas.user import UserOut
from backend.crud import user as crud
from backend.api.deps import get_current_user

router = APIRouter(prefix="/users", tags=["users"])


# 必须把 /me 路由放在 /{user_id} 路由之前！
@router.get("/me", response_model=UserOut)
async def read_current_user(current_user: UserOut = Depends(get_current_user)):
    """
    获取当前登录用户信息
    """
    return current_user


@router.get("/", response_model=list[UserOut])
async def read_users(
        skip: int = 0,
        limit: int = 100,
        db: AsyncSession = Depends(get_db),
        current_user: UserOut = Depends(get_current_user)
):
    """
    获取用户列表（需要管理员权限）
    """
    users = await crud.get_users(db, skip=skip, limit=limit)
    return users


@router.get("/{user_id}", response_model=UserOut)
async def read_user(
        user_id: str,
        db: AsyncSession = Depends(get_db),
        current_user: UserOut = Depends(get_current_user)
):
    """
    根据ID获取用户信息
    """
    # 验证 user_id 是否为有效的 UUID
    try:
        import uuid
        uuid.UUID(user_id)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid user ID format")

    user = await crud.get_user(db, user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user


@router.delete("/{user_id}")
async def delete_user(
        user_id: str,
        db: AsyncSession = Depends(get_db),
        current_user: UserOut = Depends(get_current_user)
):
    """
    删除用户
    """
    try:
        import uuid
        uuid.UUID(user_id)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid user ID format")

    success = await crud.delete_user(db, user_id)
    if not success:
        raise HTTPException(status_code=404, detail="User not found")
    return {"status": "success"}